﻿
using Newtonsoft.Json;
using UnityEditor;
using UnityEditor.PackageManager;
using UnityEngine;
using UnityEngine.Networking;
using XFGameFramework.Localization;

/// <summary>
/// 翻译具体某一个配置
/// </summary>
public class TranslateLanguageInfoWindow : EditorWindow
{
    private MultiLanguageConfigs multiLanguageConfigs;

    private LanguageConfig languageConfig;
    
    private LanguageInfo languageInfo;
      
    private SystemLanguage from;
      
    private TranslateAPI api;

    // 术语表
    private bool need_intervene = true;

    // 术语表id
    private string vocab_id;


    private GUIContent fromContent;

    private GUIContent toContent;

    private GUIStyle dropdownStyle;

    private UnityWebRequest request;

    private string error;
    
    private GUIStyle errorStyle; 

    public void ShowLanguageInfo( MultiLanguageConfigs multiLanguageConfigs,LanguageConfig languageConfig,LanguageInfo languageInfo)
    { 
        this.multiLanguageConfigs = multiLanguageConfigs;
        this.languageConfig = languageConfig;
        this.languageInfo = languageInfo;

        LanguageConfig fromConfig = multiLanguageConfigs.GetLanguageConfigData(LocalizationManager.Language);

        if (fromConfig != null && LocalizationManager.Language != languageConfig.language)
        {
            from = LocalizationManager.Language;
        }
        else
        {
            foreach (var item in multiLanguageConfigs.Languages)
            {
                if (item.language == languageConfig.language) continue;
                fromConfig = item;
                from = item.language;
                break;
            }
        }

        

    }
     
    private void OnGUI_From()
    {
        if (fromContent == null)
            fromContent = new GUIContent();

        fromContent.text = from.ToString();

        EditorGUILayout.LabelField(string.Empty, "源语言", "BoldLabel");

        if (dropdownStyle == null)
            dropdownStyle = new GUIStyle("DropDown");


        GUILayout.BeginHorizontal();

        EditorGUILayout.LabelField("from", GUILayout.Width(148));

        Rect r = GUILayoutUtility.GetRect(fromContent, dropdownStyle, GUILayout.ExpandWidth(true));
        if (EditorGUI.DropdownButton(r, fromContent, FocusType.Passive, dropdownStyle))
        {
            GenericMenu menu = new GenericMenu();

            foreach (var item in multiLanguageConfigs.Languages)
            {
                if (item.language == languageConfig.language)
                {
                    menu.AddDisabledItem(new GUIContent(item.language.ToString()));
                }
                else
                {
                    menu.AddItem(new GUIContent(item.language.ToString()), from == item.language, () =>
                    {
                        from = item.language;
                    });
                }

            }

            menu.DropDown(r);
        }

        GUILayout.EndHorizontal();


        EditorGUI.BeginDisabledGroup(true);

        GUILayout.BeginHorizontal();

        GUILayout.FlexibleSpace();

        LanguageConfig l = multiLanguageConfigs.GetLanguageConfigData(from);

        if (l != null) 
        {
            LanguageInfo i = l.GetLanguageInfo(languageInfo.id); 
            GUILayout.Label(i.str );
        }



        GUILayout.EndHorizontal();
        EditorGUI.EndDisabledGroup();
    }


    private void OnGUI_To()
    {
        if (toContent == null)
            toContent = new GUIContent();

        toContent.text = languageConfig.language.ToString();

        EditorGUI.BeginDisabledGroup(true);

        EditorGUILayout.LabelField(string.Empty, "目标语言", "BoldLabel");

        if (dropdownStyle == null)
            dropdownStyle = new GUIStyle("DropDown");


        GUILayout.BeginHorizontal();

        EditorGUILayout.LabelField("to", GUILayout.Width(148));

        Rect r = GUILayoutUtility.GetRect(toContent, dropdownStyle, GUILayout.ExpandWidth(true));
        EditorGUI.DropdownButton(r, toContent, FocusType.Passive, dropdownStyle);
          
        GUILayout.EndHorizontal();

        EditorGUI.EndDisabledGroup();


    }

    private void OnGUI_Api()
    {
        GUILayout.Space(5);
        EditorGUILayout.LabelField(string.Empty, "翻译Api", "BoldLabel");
        api = (TranslateAPI)EditorGUILayout.EnumPopup("api", api);
    }

    private void OnGUI_Intervene()
    {
        GUILayout.Space(5);

        switch (api)
        {
            case TranslateAPI.Baidu:
                EditorGUILayout.LabelField(string.Empty, "术语表", "BoldLabel");
                need_intervene = EditorGUILayout.Toggle("need_intervene", need_intervene);
                break;
            case TranslateAPI.Youdao:
                EditorGUILayout.LabelField(string.Empty, "术语表id", "BoldLabel");
                vocab_id = EditorGUILayout.TextField("vocab_id", vocab_id);
                break;
        }

    }

    private void OnGUI_Translate()
    {

        GUILayout.Space(10);

        if (GUILayout.Button("翻译"))
        {

            

            error = string.Empty;

            LanguageConfig l = multiLanguageConfigs.GetLanguageConfigData(from);
            LanguageInfo i = l.GetLanguageInfo(languageInfo.id);

            if (string.IsNullOrEmpty(i.str))
            {
                ShowNotification(new GUIContent("源字符串为空!"));
            }
            else
            {
                switch (api)
                {
                    case TranslateAPI.Baidu:

                        if (string.IsNullOrEmpty(LocalizationSettings.Instance.baidu.app_id) || string.IsNullOrEmpty(LocalizationSettings.Instance.baidu.secret_key))
                        {
                            if (EditorUtility.DisplayDialog("提示", "app_id 或 密钥为空,请设置后再试!", "打开设置")) 
                                LocalizationSettings.Instance.OpenProjectSettings("XFGameFramework/Localization");
                            return;
                        }

                        request = TranslateController.TranslateBaidu(from, languageConfig.language, i.str, need_intervene ? 1 : 0);

                        break;
                    case TranslateAPI.Youdao:

                        if (string.IsNullOrEmpty(LocalizationSettings.Instance.youdao.app_id) || string.IsNullOrEmpty(LocalizationSettings.Instance.youdao.secret_key))
                        {
                            if( EditorUtility.DisplayDialog("提示", "app_id 或 密钥为空,请设置后再试!", "打开设置"))
                                LocalizationSettings.Instance.OpenProjectSettings("XFGameFramework/Localization");
                            return;
                        }

                        request = TranslateController.TranslateYoudao(from, languageConfig.language, i.str, vocab_id);

                        break;
                } 
            }

        }
    }

    private void OnGUI()
    {
        OnGUI_From();

        OnGUI_To();

        OnGUI_Api();

        OnGUI_Intervene();

        if (request == null)
            OnGUI_Translate();

        if (errorStyle == null) 
        {
            errorStyle = new GUIStyle(GUI.skin.label);
            errorStyle.normal.textColor = Color.red;
        }

        EditorGUILayout.LabelField(error, errorStyle);
    }


    private void Update()
    {
        
        if(request == null) return;

        if (request.isDone) 
        {
            switch (api)
            {
                case TranslateAPI.Baidu:

                    BaiduTranslateResult baidu_result = JsonConvert.DeserializeObject<BaiduTranslateResult>(request.downloadHandler.text);


                    if (baidu_result != null)
                    {
                        if (!baidu_result.isError)
                        {
                            // 成功
                            SetResult(baidu_result.result);
                        }
                        else
                        {
                            error = baidu_result.error;
                        }
                    }
                    else
                    {
                        error = "翻译出错,请稍后再试!";
                    }


                    break;
                case TranslateAPI.Youdao:

                    YoudaoTranslateResult youdao_result = JsonConvert.DeserializeObject<YoudaoTranslateResult>(request.downloadHandler.text);

                    if (youdao_result != null)
                    {
                        if (!youdao_result.isError)
                        {
                            // 成功  
                            SetResult(youdao_result.result);
                        }
                        else
                        {
                            error = youdao_result.error;
                        }
                    }
                    else 
                    {
                        error = "翻译出错,请稍后再试!";
                    }

                    break;
            }

            

            request = null;
        }

    }

    private void SetResult(string str) {
        languageInfo.str = str;
        languageConfig.Save();
        Close();

        EditorUtility.DisplayDialog("提示", "翻译成功", "确定");
    }


    private void OnLostFocus()
    {
        Close();
    }

}
